/*
 * Copyright (C) 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.gapid;

import java.util.HashMap;
import java.util.Map;

/**
 * Cache is an in-memory key-value store. Values are generated by the {@link Cache.Builder} when
 * there is a cache-miss.
 * @param <K> the cache key type.
 * @param <V> the cache value type.
 */
public class Cache<K, V> {
    private final Map<K, V> map = new HashMap<>();
    private final Builder<K, V> builder;

    /**
     * Builder generates new values when there is a cache miss.
     * @param <K> the cache key type.
     * @param <V> the cache value type.
     */
    interface Builder<K, V> {
        V build(K key);
    }

    public static <K, V> Cache<K, V> create(Builder<K, V> builder) {
        return new Cache<>(builder);
    }

    /**
     * Lookups the value from the cache using the given key. If the cache does not contain the value
     * then the {@link Builder} will be used to create the value.
     */
    public V get(K key) {
        synchronized (map) {
            if (map.containsKey(key)) {
                return map.get(key);
            }
        }
        V value = builder.build(key);
        synchronized (map) {
            map.put(key, value);
        }
        return value;
    }

    private Cache(Builder<K, V> builder) {
        this.builder = builder;
    }
}
